<?php

namespace app\admin\controller;

use app\common\controller\BasicAdmin;
use app\common\model\UserModel;
use app\common\traits\SelectPage;
use app\common\model\CourseAttendanceModel;
use app\common\model\CourseModel;
use app\common\model\UserTimesModel;

class Classmaster extends BasicAdmin
{
    use SelectPage;
    public $model = 'UserModel';

    /**
     * 班主任列表
     */
    public function index()
    {
        return $this->_query($this->model)
            ->equal('school_id')
            ->equal('grade_id')
            ->equal('class_id')
            ->like('realname,phone')
//            ->append(['poster_paylog_total'])
            ->where('role', 3)
            ->page();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $user_id = $this->request->get('id');
        $user =  UserModel::where('id',$user_id)->with(['school','schoolgrade','schoolclass'])->find();
        //班主任的话计算学生数与课程数
        $user['student_count'] = UserModel::where('class_id',$user['class_id'])
            ->where('role',1)->count();
        $user['course_count'] =  CourseModel::where('class_id',$user['class_id'])->count();
        //缺勤率
        $course_ids = CourseModel::where('class_id',$user['class_id'])
            ->field('group_concat(id) as course_ids')->find()['course_ids'];
        $attendance_count = CourseAttendanceModel::where('course_id','in',$course_ids)->count();
        $attendance = CourseAttendanceModel::where('course_id','in',$course_ids)->select();
        $rate = 0;
        foreach ($attendance as $key=>&$value){
            if(count(explode(',',$value['all_userids']))!=0){
                $rate += count(explode(',',$value['away_userids']))/count(explode(',',$value['all_userids']));
            }
        }
        if($attendance_count>0){
            $attendance_rate = $rate/$attendance_count;
        }else{
            $attendance_rate = 0;
        }

        $user['attendance_rate'] = round($attendance_rate,4)*100;
        $this->assign('user',$user);
        $this->fetch();
    }

    /**
     * 设置真实姓名
     */
    public function set_realname()
    {
        $this->title = '编辑';
        return $this->_form($this->model, 'realname');
    }
}